#pragma once
#include<iostream>
#include<sys/epoll.h>
#include<cerrno>
#include<cstdlib>
#include<unistd.h>
#include"Log.hpp"

#define GSIZE 1024

class Epoller
{
public:
    //创建函数方法 采用静态成员函数
    static int CreateEpoller()
    {
        int epfd = epoll_create(GSIZE);
        if(epfd < 0)
        {
            logMessage(FATAL,"epoll create error %d, %s",errno,strerror(errno));
            exit(3);
        }
        return epfd;
    }

    //向某个epoll套接字中添加,指定的sock添加它所关心的事件
    static bool AddEvent(int epfd,int sock, uint32_t event)
    {
        struct epoll_event ev;
        ev.events = event;
        ev.data.fd = sock;
        
        int n = epoll_ctl(epfd,EPOLL_CTL_ADD, sock, &ev);

        return n == 0;
    }

    //获取已经就绪的事件
    static int LoopOnce(int epfd, struct epoll_event revs[], int num)
    {
        //阻塞等待 -1
        int n = epoll_wait(epfd,revs,num,-1);
        if(n == -1)
        {
            logMessage(FATAL,"epoll wait error %d : %s\n", errno, strerror(errno));
        }
        return n;
    }

    //从event中移除fd
    static bool DeleteEvent(int epfd, int sock)
    {
        int n = epoll_ctl(epfd,EPOLL_CTL_DEL, sock, nullptr);

        return n==0;
    }

    static bool ModEvent(int epfd, int sock, uint32_t event)
    {
        struct epoll_event ev;
        ev.events = event;
        ev.data.fd = sock;
        int n = epoll_ctl(epfd,EPOLL_CTL_MOD,sock,&ev);
        return n == 0;
    }
};

